/*appLang = {
	CAN_NOT_BE_PREFORMED :  'Action can not be performed',
    CONFIRM				 :	'Confirm',
    CANCEL				 :  'Cancel',
    DELETE_SURE			 :	'Are you sure you want to delete',
	MSG					 :	'Message',
	FILL_CORRECTLY		 :	'Please fill out form correctly',
	LOADING				 :	'Loading...',
	SERVER_NOT_RESPONDING:	'Server is not responding',
	SAVE				 :	'Save',
	SAVING				 :  'Saving...',
	ERROR_REUIRED_COLUMNS:	'Not all of the required columns are identified',
	IMPORT_COMPLETED	 :	'Data import successfully completed'
};
*/

app.Import= Ext.extend(Ext.Panel,{
	uploadForm:null,
	importForm:null,
	impotrtFormContainer:null,
	gridContainer:null,
	dataGrid:null,
	layout:'border',
	title:'Import',
	expectedColumns:[
	    {id:'prefix',text :'Prefix' , columnIndex:-1},
	    {id:'cost',text :'Cost',columnIndex:-1}	
	],
	constructor: function(config) {
		config = Ext.apply({ 
	        border:false,
	        bodyBorder:false,
	        items:[]
	    }, config);						
		app.Import.superclass.constructor.call(this , config);
	},

	initComponent:function(){
		this.uploadForm = new Ext.form.FormPanel({
			region:'north',
			padding:3,
			fileUpload:true,
			frame:true,
			labelWidth:1,
			height:80,
			buttonAlign:'left',
			items:[
			    	  {
			  	    	    xtype: 'fileuploadfield',
			  	    	    emptyText: 'Select file to import',
			  		        buttonText: '',
			  		        buttonCfg: {
			  		            iconCls: 'upload-icon'
			  		        },
			  	    	    name:'file',
			  	    	    width:300,
			  	    	    fieldLabel:''
			  	       }
			      
			],
			buttons:[{
				text:'Upload',
				listeners:{
					click:{
						fn:this.uploadFile,
						scope:this
					}
				}
			}]
		});
		
		
		var expFields = [];
		Ext.each(this.expectedColumns , function(item){
			expFields.push({xtype:'displayfield' , name:item.id , fieldLabel:item.text , value:'<img src="/img/no.png">'});
		},this);
		
		
		this.importForm = new Ext.form.FormPanel({
			padding:2,
			fileUpload:false,
			frame:true,
			labelWidth:60,
			autoScroll:true,
			hidden:true,
			title:'Import Configuration',
			items:[
			       {
			    	   xtype:'fieldset',
			    	   title:'Expected Columns',
			    	   items:[expFields]
			       },
			       {
			    	   xtype:'fieldset',
			    	   title:'Import type',
			    	   items:[
			    	           {
								   xtype:'radiogroup',
								   columns:1,	
								   hideLabel:true,
								   items:[
								      {name:'type' , inputValue:1, boxLabel:'Rewrite'},
								      {name:'type' , inputValue:2, boxLabel:'Update', checked:true},
								   ]
						       }
			    	   ]
			       }				       
			],
			buttons:[
			   {
				   text:'Import',
				   listeners:{
					   click:{
						   fn:this.importData,
						   scope:this
					   }
				   }
			   }      
			]
		});
		
		this.gridContainer = new Ext.Panel({
			items:[],
			frame:false,
			layout:'fit',
			region:'center',
			border:false
		});
		
		this.importFormContainer = new Ext.Panel({
			frame:false,
			layout:'fit',
			region:'east',
			width:250,
			items:[this.importForm],
			border:false
		});
		
		this.items = [this.uploadForm , this.gridContainer, this.importFormContainer];
		
		app.Import.superclass.initComponent.call(this);
	},
	uploadFile:function(){
		var handle = this;
		this.uploadForm.getForm().submit({
			clientValidation: true,
			waitMsg: appLang.SAVING,
			method:'post',
			url:this.controllerUrl + 'upload/',
			success: function(form, action) {	
  		 		if(!action.result.success){
  		 			handle.importForm.hide();
  		 			Ext.Msg.alert(appLang.MSG, action.result.msg);
  		 			return;
  		 		} else{
  		 			handle.showRecords(action.result.data ,action.result.col_count );
  		 		}
  	        },
  	        failure: app.formFailure
  	    });
	},
	showRecords:function(data , colCount){
		if(Ext.isEmpty(data)){
			return;
		}
		
		var dataColumns = [];
		var dataFields = [];
		
		for(var i=0;i<colCount;i++){
			dataColumns[dataColumns.length] = {
				header: 'Column '+ (i+1),
				dataIndex: 'col'+i,
				id:'col'+i
			};
			dataFields[dataFields.length] = {
					name:'col'+i,
					type:'string'
			};
		}
		
		this.dataGrid = new Ext.grid.GridPanel({
				autoScroll: true,
				frame: false,
				loadMask:true,
				stripeRpws:true,
				columnLines:true,
				enableColumnResize:false,
				enableColumnMove : false,
				enableColumnHide : false,
				enableHdMenu:true,
				cm: new Ext.grid.ColumnModel({
			          defaults: {
			              sortable: false,
			              menuDisabled: true,
			              width:65 
			          },
					  columns:dataColumns				  	  
				}),
				store:new Ext.data.JsonStore({
					  fields:dataFields,
					  autoLoad:false,
					  data:data
					  
				}),
				listeners:{
					headerclick:{
						fn:this.showHeaderMenu,
						scope:this		
					}
				}
		});
		
		
		this.gridContainer.removeAll();
		this.gridContainer.add(this.dataGrid);
		this.gridContainer.syncSize();
		this.importForm.getForm().reset();
		
		Ext.each(this.expectedColumns , function(item){
			this.importForm.getForm().findField(item.id).setValue('<img src="/img/no.png">');
		},this);
		
		this.importForm.show();
	},
	showHeaderMenu: function showMenu(grid, index, event) {
	      event.stopEvent();
	      var menu = new Ext.menu.Menu();
	      var record = grid.getStore().getAt(index);
	      var handle = this;
	      
	      var columnId = grid.getColumnModel().getColumnId(index);
	      
	      menu.addMenuItem({
	    		  text: 'Column ' + (index+1),
	    		  listeners:{
   				  click:{
   					  fn:function(btn){
   						  this.columnIdentified(index , -1);
   					  },
   					  scope:this
   				  }
   			  }
	      });
	
	      Ext.each(this.expectedColumns , function(record){
	    	  menu.addMenuItem({
   			  text:record.text,
   			  listeners:{
   				  click:{
   					  fn:function(btn){
   						  this.columnIdentified(index , record.id);
   					  },
   					  scope:this
   				  }
   			  }
	    	  });
	      },this);   
	      menu.showAt(event.xy);
	},
	columnIdentified:function(colIndex , key){
		var cm = this.dataGrid.getColumnModel();
		var iForm = this.importForm.getForm();
		if(key==-1){
			Ext.each(this.expectedColumns , function(record){
				if(record.columnIndex == colIndex){
					record.columnIndex = -1;
					iForm.findField(record.id).setValue('<img src="/img/no.png">');
				}		
			},this);
			cm.setColumnHeader( colIndex, 'Column '+ (colIndex+1));
			
		}else{
			Ext.each(this.expectedColumns , function(record){
				
				if(record.id == key && record.columnIndex != colIndex && record.columnIndex !=-1){			
					cm.setColumnHeader( record.columnIndex, 'Column '+ (record.columnIndex+1));
					record.columnIndex = -1;
				} 
				
				if(record.id == key){
				   record.columnIndex = colIndex;
				   cm.setColumnHeader( record.columnIndex, '<div class="importSelected">&nbsp;'+record.text+'</div>');
				   iForm.findField(record.id).setValue('<img src="/img/yes.gif">');
				}
				
			},this);		
		}
	},
	importData:function(){
		var invalid = false;
		var params = {};
		Ext.each(this.expectedColumns , function(record){
				if(record.columnIndex == -1){
					invalid = true;
				}
				params['columns['+record.id+']'] = record.columnIndex;
		});
		
		if(invalid){
			Ext.Msg.alert(appLang.MSG, appLang.ERROR_REUIRED_COLUMNS);
			return;
		}
		
		var handle = this;
		
		
		this.importForm.getForm().submit({
			clientValidation: true,
			waitMsg: appLang.SAVING,
			method:'post',
			url:this.controllerUrl + 'import/',
			params:params,
			success: function(form, action) {	
  		 		if(!action.result.success){
  		 			Ext.Msg.alert(appLang.MSG, action.result.msg);
  		 		} else{
  		 			Ext.Msg.alert(appLang.MSG, appLang.IMPORT_COMPLETED); 
  		 		}
  	        },
  	        failure: app.formFailure
  	    });
	}
});